<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button type="danger" @click="benchDelete">批量删除</el-button>
    <el-button v-if="draggable" @click="benchSave">批量保存</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            Edit
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json

//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      pCid: [], //批量保存后需要展开的父节点数组
      draggable: false,
      updateNodes: [],
      maxLevel: 0,
      dialogType: "",
      title: "",
      dialogVisible: false,
      menus: [],
      category: {
        catId: null,
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: ""
      },
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(response => {
        //解构data
        console.log("成功获取到菜单数据.....", response.data[""]);
        this.menus = response.data[""];
      });
    },
    benchDelete() {
      let catIds = [];
      let names = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中的节点:" + JSON.stringify(checkedNodes));
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
        names.push(checkedNodes[i].name);
      }
      this.$confirm(`是否批量删除『${names}』菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ response }) => {
            this.$message({
              type: "success",
              message: "菜单批量删除成功!"
            });
            //刷新出新的树结构
            this.getMenus();
            //设置需要默认展开的菜单
            this.expandedKey = [this.category.parentCid];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除!"
          });
        });
    },
    benchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "菜单顺序修改成功!"
        });
        //刷新出新菜单
        this.getMenus();
        //设置默认需要展开的菜单
        this.expandedKey = this.pCid;
        //清空数值，防止因为不是初始值干扰下一下拖拽
        this.updateNodes = [];
        this.maxLevel = 0;
        this.pCid = [];
      });
    },
    //判断是否能拖拽
    allowDrop(draggingNode, dropNode, type) {
      //1、被拖动的当前节点以及所在的目标节点总层数不能大于3

      //1）、被拖动的当前节点draggingNode dropNode:目标节点 type:节点所在位置
      console.log("draggingNode:", draggingNode, dropNode, type);
      this.maxLevel = 0;
      this.countNodeLevel(draggingNode);
      // console.log("countNodeLevel方法被调用...........");
      //当前正在拖动的节点+目标节点的深度不大于3即可
      let deep = Math.abs(this.maxLevel - draggingNode.level + 1);
      // console.log("this.maxLevel: " + this.maxLevel);
      // console.log("被拖动节点的深度: " + deep);
      // console.log("draggingNode.level: " + draggingNode.level);
      // console.log("dropNode.level: " + dropNode.level);
      // console.log("dropNode.parent.level: " + dropNode.parent.level);
      // console.log("------------------------------");
      if (type == "inner") {
        // console.log(
        //   `this.maxLevel:${this.maxLevel};draggingNode.data.catLevel:${
        //     draggingNode.data.catLevel
        //   };dropNode.level:${dropNode.level}`
        // );
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevelError(node) {
      //此方法为视频中错误代码，下面的那个方法是正确的
      // 找到当前节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]); //递归
        }
      }
    },
    countNodeLevel(node, currentLevel = 0) {
      //计算当前节点的最大深度
      if (node.level > currentLevel) {
        currentLevel = node.level;
      }
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.countNodeLevel(node.childNodes[i], currentLevel);
        }
      }
      if (currentLevel > this.maxLevel) {
        this.maxLevel = currentLevel;
      }
    },
    //节点拖拽成功之后触发的事件,需重新计算拖动节点的level，catId和parentCid，因为数据库和页面的不是对应的
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // this.updateNodes = [];
      console.log("拖拽成功的节点: ", draggingNode, dropNode, dropType);
      //当前节点的最新父节点id
      let pCid = 0;
      let siblings = null; //兄弟节点(同一父节点的一级子节点)
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes; //如果为before或after，根据父节点的子节点顺序排序
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes; //如果为inner，根据目标节点子节点的顺序排序
      }
      this.pCid.push(pCid);
      //当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是当前正在拖拽的节点，还应修改父id
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //当层级发生改变
            catLevel = siblings[i].level;
            //修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      //3.当前拖拽节点的最新顺序
      console.log("updateNods:" + JSON.stringify(this.updateNodes));
    },
    //修改子节点的层级
    updateChildNodeLevel(node) {
      for (let i = 0; i < node.childNodes.length; i++) {
        if (node.childNodes.length > 0) {
          var currentNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: currentNode.catId,
            catLevel: node.childNodes[i].level
          });
          //递归修改子节点层级
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },

    submit() {
      if (this.dialogType === "add") {
        this.addCategory();
      }
      if (this.dialogType === "edit") {
        this.editCategory();
      }
    },
    edit(data) {
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.title = "编辑分类";
      // console.log("dialogType:", this.dialogType);
      //发送请求，查询当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
        this.category.catLevel = data.data.catLevel;
        this.category.sort = data.data.sort;
        this.category.showStatus = data.data.showStatus;
      });
    },
    //修改三级分类
    editCategory() {
      var { name, catId, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        //直接把结构出来的name,catId,icon,productUnit返回给服务器，没有被返回的服务器默认为null，不会受到前段给的默认值的影响
        data: this.$http.adornData({ name, catId, icon, productUnit }, false) //this.category里面的数据都在edit方法里面回显，无须担心默认值影响
      }).then(({ data }) => {
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的树结构
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentCid];
        this.$message({
          type: "success",
          message: "菜单修改成功!"
        });
      });
    },
    append(data) {
      console.log("append", data);
      this.dialogVisible = true;
      this.dialogType = "add";
      this.title = "添加分类";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1; //根据父级的层级添加分类，所以子分类的层级加一
      this.category.catId = null;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
    },
    addCategory() {
      console.log("添加的菜单信息:", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {});
      //关闭对话框
      this.dialogVisible = false;
      //刷新出新的树结构
      this.getMenus();
      //设置需要默认展开的菜单
      this.expandedKey = [this.category.parentCid];
      this.$message({
        type: "success",
        message: "菜单添加成功!"
      });
    },
    remove(node, data) {
      console.log("remove", node, data);
      var ids = [data.catId];
      this.$confirm(`是否删除『${data.name}』菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ response }) => {
            this.$message({
              type: "success",
              message: "菜单删除成功!"
            });
            //刷新出新的树结构
            this.getMenus();
            //设置需要默认展开的菜单
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合

  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
